import { observable, action } from 'mobx';
import { ListAdvanced } from 'weaver-mobile-page';
import * as Apis from "../../api/customerApis";
import { Toast, Tools, Bubble } from 'weaver-mobile';
import { MapPage, RouteLayout, Reply } from 'weaver-mobile-page';
import { toJS } from 'mobx';
import * as adapter from '../../constants/adapter';
const getLabel = Tools.getLabel;
const getCurrentPosition = MapPage.getCurrentPosition;
export default class CrmListStore {
  comObj = {};
  params = {};
  curCustomerId;
  currentPosition = [];
  @observable type = [];
  @observable listTab = [];
  @observable listTabKey = "";
  @observable listTabIndex = "my";
  @observable showCheck = false;
  @observable listAd = {};
  @observable initResponsed = false;// 是否已经得到初始化数据的响应
  @observable initSuccessed = false;// 初始化数据是否获取成功
  @observable initFailedMsg = "";   // 初始化处理失败的原因
  @observable isOpenCardScan = 0;
  @observable manager = { id: "", name: "", initname: "" };
  @observable isShowResource = false;
  @observable leftTreeValueArray = [];
  @observable cardLayout = {};
  @observable contactLayout = {};
  @observable createLayout = {};
  @observable createLayoutScan = {};
  @observable replyStore = new Reply.Store({ getAttachList: this.getAttachList });
  @observable contactWay = [];

  @action
  doNew = (comObj, params) => {
    // console.log("doNew");
    this.comObj = comObj;
    this.params = params;
    this.type = params.type;
    this.listTabIndex = params.listTabIndex;
    window.crmGlobal = this;
  }

  @action
  doInit = () => {
    // console.log("doInit");
    let params = this.params;
    Apis.getHearderTab(params).then(data => {
      this.doInitCallBack(params, data);
    });
  }

  @action
  doInitCallBack = (params, data) => {
    this.initResponsed = true;
    if (data.status == "0") {
      this.initSuccessed = false;
      this.initFailedMsg = data.errorMsg;
    } else {
      this.initSuccessed = true;
      this.listTab = data.tabs;
      this.listTabKey = data.keyParam;
      if (this.type == "crm_list" || this.type == "crm_partner" || this.type == "crm_contacter") {
        this.isOpenCardScan = data.isOpenCardScan;
      }
      if (this.type == "crm_list" || this.type == "crm_partner") {
        this.isShowResource = data.isShowResource;
        this.manager.initname = data.resourcename;
      }
      const currentPath = this.comObj.props.location.pathname;
      this.cardLayout = new RouteLayout.Store({ route: currentPath, id: 'cardLayout' });
      this.contactLayout = new RouteLayout.Store({ route: currentPath, id: 'contactLayout' });
      this.createLayout = new RouteLayout.Store({ route: currentPath, id: 'createLayout' });
      this.createLayoutScan = new RouteLayout.Store({ route: currentPath, id: 'createLayoutScan' });
      this.listAd = new ListAdvanced.Store({ route: currentPath, id: "ad" });
      this.doSearch();
      this.contactWay = data.contactWay || [];

    }
  }

  @action
  doClear = () => {
    // console.log("doClear");
    this.listTabIndex = "my";
    this.initResponsed = false;
    this.initSuccessed = false;
    this.initFailedMsg = "";
    this.manager.id = "";
    this.manager.name = "";
    this.isShowResource = false;
    this.leftTreeValueArray = [];
  }

  @action
  doSearch = () => {
    // console.log("doSearch");
    const { searchAdvancedStore, listViewStore, searchParams } = this.listAd;
    // 搜索框等搜索数据
    let params = {};
    // 获取高级搜索参数
    if (searchAdvancedStore) {
      const { formParams } = searchAdvancedStore.form;
      params = { ...this.params, ...formParams, ...searchParams };
    } else {
      params = { ...this.params, ...searchParams };
    }
    params[this.listTabKey] = this.listTabIndex;
    if (this.manager.id) {
      params.manager = this.manager.id;
    }
    // 清除列表数据
    listViewStore.clearData();
    // 获取当前位置
    if (this.listTabIndex == "around") {
      if (!params.raidus) {
        params.raidus = 10;
      }
      let aroundTitle = this.listTab[3].title;
      const indexS = aroundTitle.indexOf("(");
      let aroundTitleNew = aroundTitle.substring(0, indexS);
      this.listTab[3].title = aroundTitleNew + "(" + params.raidus + "km)";
      if (this.currentPosition.length == 0) {
        getCurrentPosition().then((result) => {
          this.currentPosition = result.position;
          params["lng"] = this.currentPosition[0];
          params["lat"] = this.currentPosition[1];
          this.listAd.getData({ url: '/api/crm/mobile/getCustomerListResult', params });
        });
      } else {
        params["lng"] = this.currentPosition[0];
        params["lat"] = this.currentPosition[1];
        this.listAd.getData({ url: '/api/crm/mobile/getCustomerListResult', params });
      }
    } else {
      let dataUrl = "";
      const type = this.type;
      if (type == "crm_list" || type == "crm_partner") {
        dataUrl = "/api/crm/mobile/getCustomerListResult";
      } else if (type == "crm_chance") {
        dataUrl = "/api/crm/mobile/getChanceListResult";
      } else if (type == "crm_contacter") {
        dataUrl = "/api/crm/mobile/getContacterListResult";
      }
      this.listAd.getData({ url: dataUrl, params });
    }
  }

  @action
  reload(params) {
    this.doClear();
    this.doNew(this.comObj, params);
    this.doInit();
  }

  @action
  topTabChange = (selectedIndex) => {
    this.manager.id = "";
    this.manager.name = "";
    this.leftTreeValueArray = [];
    this.listTabIndex = selectedIndex;
    this.listAd.searchAdvancedStore.form.resetConditions();
    const currentPath = this.comObj.props.location.pathname;
    this.cardLayout = new RouteLayout.Store({ route: currentPath, id: 'cardLayout' });
    this.contactLayout = new RouteLayout.Store({ route: currentPath, id: 'contactLayout' });
    this.createLayout = new RouteLayout.Store({ route: currentPath, id: 'createLayout' });
    // this.listAd = new ListAdvanced.Store({ route: currentPath, id: "ad" });
    let conditionUrl = "";
    const type = this.type;
    const listTabIndex = this.listTabIndex;
    if (type == "crm_list" || type == "crm_partner") {
      conditionUrl = "/api/crm/mobile/getCustomerCondition?opt=" + listTabIndex;
    } else if (type == "crm_chance") {
      conditionUrl = "/api/crm/mobile/getChanceCondition?opt=" + listTabIndex;
    } else if (type == "crm_contacter") {
      conditionUrl = "/api/crm/mobile/getContacterCondition?opt=" + listTabIndex;
    }
    this.listAd.searchAdvancedStore.getData({ url: conditionUrl });
    this.doSearch();
  }

  @action
  barTabChange = (type, listTabIndex) => {
    this.reload({ type: type, listTabIndex: listTabIndex });
  }

  @action
  onLeftTreeChange(id, name, valuearray) {
    this.manager.id = id;
    this.manager.name = name;
    this.leftTreeValueArray = valuearray;
    this.doSearch();
  }

  @action
  resetReplyStore = (customerId) => {
    this.curCustomerId = customerId;
    this.replyStore = new Reply.Store({ getAttachList: this.getAttachList });
    this.replyStore.doInit();
  }

  getAttachList = () => { // 添加操作内 attach配置
    const customerId = this.curCustomerId;
    return new Promise((resolve) => {
      const currentPath = this.comObj.props.location.pathname;
      const browserPath = currentPath + "/browser";
      const uploadPath = currentPath + "/upload";
      const contactWays = toJS(this.contactWay);
      resolve({
        attachList: [
          {
            key: 'workFlow', // 字符串
            type: 'browser',
            path: browserPath,
            config: {
              type: 16,
              isSingle: false,
              hasAdvanceSerach: true
            },
            iconType: 'flow',
            iconBgColor: '#61A8F5',
            text: getLabel("18015", '流程'),
          },
          {
            key: 'document',
            type: 'browser',
            path: browserPath,
            config: {
              type: 9,
              isSingle: false,
            },
            iconType: 'file',
            iconBgColor: '#61A8F5',
            text: getLabel("58", '文档'),
          },
          {
            key: 'project',
            type: 'browser',
            path: browserPath,
            config: {
              type: 8,
              isSingle: false,
            },
            iconType: 'relevant-project',
            iconBgColor: '#61A8F5',
            text: getLabel("101", '项目'),
          },
          // {
          //   key: 'task',
          //   type: 'browser',
          //   path: browserPath,
          //   config: {
          //     type: "prjtsk",
          //     isSingle: false,
          //   },
          //   iconType: 'task',
          //   iconBgColor: '#61A8F5',
          //   text: getLabel("1332",'任务'),
          // },
          {
            key: 'chance',
            type: 'browser',
            path: browserPath,
            config: {
              type: "sellchance",
              isSingle: true,
              dataParams: { customer: customerId }
            },
            iconType: 'asset',
            iconBgColor: '#61A8F5',
            text: getLabel("32922", '商机'),
          },
          {
            key: 'contacter',
            type: 'browser',
            path: browserPath,
            config: {
              type: "67",
              isSingle: true,
              dataParams: { customerid: customerId }
            },
            iconType: 'customer',
            iconBgColor: '#61A8F5',
            text: getLabel("572", '联系人'),
          },
          {
            key: 'file',
            type: 'upload',
            path: uploadPath,
            config: {
              multiSelection: true,
            },
            iconType: 'file',
            iconBgColor: '#F3B04C',
            text: getLabel("156", '附件'),
          },
          { // 选择器 传type为picker
            key: 'contactWay',
            type: 'picker',
            config: {
              title: getLabel(514789, "请选择联系方式"),
              cols: 1,
              data: contactWays,
              value: [],
            },
            iconType: 'approval',
            iconBgColor: '#61A8F5',
            text: getLabel(15858, "联系方式"),
          }
        ],
      });
    })
  }

  @action
  saveReply(datas, customerId) {
    // console.log("datas",datas);
    let workflows = "";
    let docs = "";
    let projects = "";
    // let taskes = "";
    let chances = "";
    let contacters = "";
    let imgs = "";
    let attachs = "";
    let contactWay = "";
    if (datas.attach.workFlow) {
      for (let obj of datas.attach.workFlow) {
        workflows += obj.id + ",";
      }
      workflows = workflows.substring(0, workflows.length - 1);
    }
    if (datas.attach.document) {
      for (let obj of datas.attach.document) {
        docs += obj.id + ",";
      }
      docs = docs.substring(0, docs.length - 1);
    }
    if (datas.attach.project) {
      for (let obj of datas.attach.project) {
        projects += obj.id + ",";
      }
      projects = projects.substring(0, projects.length - 1);
    }
    // if(datas.attach.task){
    //   for(let obj of datas.attach.task){
    //     taskes += obj.id + ",";
    //   }
    //   taskes = taskes.substring(0,taskes.length - 1);
    // }
    if (datas.attach.chance) {
      for (let obj of datas.attach.chance) {
        chances += obj.id + ",";
      }
      chances = chances.substring(0, chances.length - 1);
    }
    if (datas.attach.contacter) {
      for (let obj of datas.attach.contacter) {
        contacters += obj.id + ",";
      }
      contacters = contacters.substring(0, contacters.length - 1);
    }
    if (datas.imgList) {
      for (let obj of datas.imgList) {
        imgs += obj.fileid + ",";
      }
      imgs = imgs.substring(0, imgs.length - 1);
    }
    if (datas.attach.file) {
      for (let obj of datas.attach.file) {
        attachs += obj.id + ",";
      }
      attachs = attachs.substring(0, attachs.length - 1);
    }
    if (datas.attach.contactWay) {
      contactWay = datas.attach.contactWay[0];
    }
    if (!datas.attach.contactWay || datas.attach.contactWay.length == 0 || contactWay == "") {
      Bubble.warning(getLabel('514789', "请选择联系方式"), 3, { backgroundColor: adapter.BUBBLE_BGCOLOR }, 2);
      return;
    }
    // console.log("workflows",workflows);
    // console.log("docs",docs);
    // console.log("projects",projects);
    // console.log("taskes",taskes);
    // console.log("chances",chances);
    // console.log("contacters",contacters);
    // console.log("imgs",imgs);
    // console.log("attachs",attachs);
    // this.replyStore.doClear();
    // console.log("replyStore",toJS(this.replyStore));
    const params = { customerId: customerId, chances: chances, contacters: contacters, description: datas.text, workflows: workflows, docs: docs, projects: projects, imgs: imgs, attachs: attachs, contactWay: contactWay }
    Toast.loading(getLabel('388626', '正在保存，请稍后...'), 0);
    this.replyRef.setVisible(false);
    Apis.saveContactForm(params).then(data => {
      Toast.hide();
      if (data.status == "0") {
        Bubble.error(getLabel(22620, '保存失败'), 1, { backgroundColor: adapter.BUBBLE_BGCOLOR }, 2, () => {

        });
      } else {
        Bubble.success(getLabel('83551', "保存成功"), 1, { backgroundColor: adapter.BUBBLE_BGCOLOR }, 2, () => {
          this.replyStore.doClear();
          // 跳转到客户卡片，激活联系记录
          this.comObj.setState({ curTabPage: "contact" });
          this.comObj.props.history.push(this.cardLayout.path);
          setTimeout(() => {
            this.comObj.setState({ curTabPage: "" });
          }, 100);
        });
      }
    });
  }
}